<?php
declare (strict_types = 1);

namespace app\backend_api\controller;

use app\backend_api\model\AdminMenus;
use app\backend_api\model\AdminRoles;
use app\backend_api\services\AuthService;
use app\BaseController;
use think\facade\Db;

class Permissions extends BaseController
{
//    protected $middleware = [
//        \app\backend_api\middleware\AuthCheck::class => [
//            'except' => 'getMenus'
//        ]
//    ];

    protected $middleware = [\app\backend_api\middleware\AuthCheck::class];

    /**
     * 角色选择权限配置列表
     * @param AuthService $AuthServices
     * @return \think\response\Json
     */
    public function getMenusSelect(AuthService $AuthService): \think\response\Json
    {
        return $this->success($AuthService::getSelectLists());
    }

    /**
     * 返回菜单列表
     * @param AuthService $AuthService
     * @return \think\response\Json
     */
    public function getMenus(AuthService $AuthService): \think\response\Json
    {
        return $this->success($AuthService::getAllMenus());
    }

    /**
     * 新增 / 修改 后台菜单
     * @return \think\response\Json
     */
    public function modifyMenu()
    {
        $input = input();
        $this->validate($input, [
            'parent_id' => 'require|number|integer',
            'menu_name' => 'require|max:64',
            'vue_component' => 'require|max:128',
            'vue_name' => 'require|max:64',
            'vue_path' => 'require|max:128',
        ]);

        $id = input('id', 0);

        if ($id) {
            AdminMenus::where('id', $id)->update($input);
        } else {
            AdminMenus::create($input);
        }

        return $this->successMsg($id ? '修改成功' : '提交成功');
    }

    /**
     * 删除菜单
     * @param $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delMenu($id)
    {
        if (!$id) {
            return $this->error('必填参数缺失！');
        }

        AdminMenus::find($id)->delete();
        return $this->successMsg('删除成功');
    }

    /**
     * 返回后台角色列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getRoleList()
    {
        return $this->success(AdminRoles::select());
    }

    /**
     * 根据角色id返回菜单ID
     * @param $id
     * @return \think\response\Json
     */
    public function getRolePid($id)
    {
        return $this->success(Db::name('admin_role_with_menus')->where('role_id', $id)->column('menu_id'));
    }

    /**
     * 后台角色权限分配
     * @return \think\response\Json
     */
    public function rolePermissions()
    {
        $input = input();
        $this->validate($input, [
            'selectPermission' => 'require|array',
            'rid' => 'require|number|integer|min:1',
        ]);
        sort($input['selectPermission']);
        $insertData = [];
        foreach ($input['selectPermission'] as $permissionId) {
            $insertData[] = [
                'role_id' => $input['rid'],
                'menu_id' => $permissionId
            ];
        }

        Db::startTrans();
        try {
            Db::name('admin_role_with_menus')->where('role_id', $input['rid'])->delete();
            Db::name('admin_role_with_menus')->insertAll($insertData);
            Db::commit();
        }catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }

        return $this->successMsg('提交成功');
    }

    /**
     * 角色 新增 / 修改
     * @return \think\response\Json
     */
    public function addRole()
    {
        $input = input();
        $this->validate($input, [
            'name' => 'require|max:8',
            'describe' => 'max:15',
            'status' => 'boolean'
        ]);

        $postData = [
            'role_name' => $input['name'],
            'role_remarks' => $input['describe'],
            'status' => $input['status']
        ];

        if (!empty($input['id'])) {
            $id = $input['id'];
            unset($input['id']);
            AdminRoles::where('id', $id)->update($postData);
            return $this->successMsg('更新成功');
        }

        AdminRoles::create($postData);
        return $this->successMsg('创建成功');
    }

    /**
     * 删除角色
     * @param $id
     * @return \think\response\Json
     */
    public function delRole($id)
    {
        if (!$id) {
            return $this->error('必填参数缺失！');
        }

        Db::startTrans();

        try {
            AdminRoles::find($id)->delete();
            Db::table('admin_with_roles')->where('role_id', $id)->delete();
            Db::table('admin_role_with_menus')->where('role_id', $id)->delete();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }

        return $this->successMsg('删除成功！');

    }
}
